package jdbc;

import bean.DbInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Conn {

	private Statement stmt;
	private Statement stmt1;
	private Statement stmt2;
	private Statement stmt3;

	/**
	 * 下面的这个就是我们的构造方法，把这个对象创建时候使用到的代码全部放到这个构造方法里面去
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
    public Conn(DbInfo dbInfo) throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://"+dbInfo.getIP()+":"+dbInfo.getPort()+"/"+dbInfo.getDatabase()+"?"+dbInfo.getTable()+"="+dbInfo.getUsername()+
				"&password="+dbInfo.getPassword()+"&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false";
		Connection con = DriverManager.getConnection(url);
		stmt = con.createStatement();
		stmt1 = con.createStatement();
		stmt2 = con.createStatement();
		stmt3 = con.createStatement();
	}

	public ResultSet query(String sql) throws SQLException {
		return stmt.executeQuery(sql);
	}

	public boolean insert(String sql) throws SQLException {
		try{
			stmt1.executeUpdate(sql);
			return true;
		}catch(Exception e){
			return false;
		}
	}

	public boolean update(String sql) throws SQLException {
		try{
			stmt2.executeUpdate(sql);
			return true;
		}catch(Exception e){
			return false;
		}
	}

	public boolean delete(String sql) throws SQLException {
		try{
			stmt3.executeUpdate(sql);
			return true;
		}catch(Exception e){
			return false;
		}
	}

	public static void main(String[] args) {

	}

	//public static void main(String[] args) {
//		try {
//			Class.forName("com.mysql.jdbc.Driver");
//			String url = "jdbc:mysql://localhost:3306/test?user=root&password=808080ZhuZhaoYu#&useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false";
//			Connection con = DriverManager.getConnection(url);
//			Statement stmt = con.createStatement();
//			Statement stmt1 = con.createStatement();
//			Statement stmt2 = con.createStatement();
//			Statement stmt3 = con.createStatement();

			//查询
//			String query = "select * from user";
//			ResultSet rs = stmt.executeQuery(query);
//			while (rs.next()) {
//				String name = rs.getString("name");
//				System.out.println(name);
//			}

//			//插入
//			String insert="insert into user value(421,'张三2',12)";
//			stmt1.executeUpdate(insert);
//
//			//修改
//			String update="update user set name='lisiert' where id=1";
//			stmt2.executeUpdate(update);
//
//			//删除
//			String del="delete from user where id=1";
//			stmt3.executeUpdate(del);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

	//}
}